import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
import { immer } from 'zustand/middleware/immer'
import { getStorage } from '@/utils/storage.ts'

export type ArtAddStore = {
  current: ArticleSteps
  article: ArticleForm
  hydrated: boolean
}

export enum Move {
  next = 1,
  prev = -1
}

export enum ArticleSteps {
  base = 0,
  cover = 1,
  content = 2,
  done = 3
}

const initState: ArtAddStore = {
  current: ArticleSteps.base,
  article: {} as ArticleForm,
  hydrated: false
}

const useArtAddStore = create<ArtAddStore>()(
  immer(
    devtools(
      persist(
        () => {
          // 初始数据
          return {
            ...initState
          }
        },
        {
          name: 'art-add-store',
          storage: getStorage<ArtAddStore>(),
          onRehydrateStorage() {
            return (_, error) => {
              if (error) {
                console.log('数据加载失败...')
              } else {
                console.log('数据加载成功！')
                useArtAddStore.setState((state) => {
                  state.hydrated = true
                })
              }
            }
          }
        }
      ),
      { name: 'art-add-store' }
    )
  )
)

export default useArtAddStore

// selectors
export const selectCurrent = (state: ArtAddStore) => state.current
export const selectBaseForm = (state: ArtAddStore) => ({ title: state.article.title, cate_id: state.article.cate_id })
export const selectCover = (state: ArtAddStore) => {
  const cover = state.article.cover_img
  return cover ? URL.createObjectURL(cover) : null
}
export const selectContent = (state: ArtAddStore) => state.article.content

// actions
export const setCurrent = (step: Move = Move.next) => {
  useArtAddStore.setState((state) => {
    state.current += step
  })
}

// 存储文章的基本信息
export const setBaseForm = (baseForm: Partial<ArticleBaseForm>) => {
  useArtAddStore.setState((state) => {
    state.article = { ...state.article, ...baseForm }
  })
}

// 存储文章的封面
export const setArticleCover = (cover: Blob) => {
  useArtAddStore.setState((state) => {
    state.article.cover_img = cover
  })
}

// 存储文章内容
export const setContent = (content: string) => {
  useArtAddStore.setState((state) => {
    state.article.content = content
  })
}

// 更新文章的发布状态
export const setState = (artState: '草稿' | '已发布') => {
  useArtAddStore.setState((state) => {
    state.article.state = artState
  })
}

// 清空文章信息
export const clearArticle = () => {
  useArtAddStore.setState((state) => {
    state.article = {} as ArticleForm
  })
}

// 重置当前 Store
export const resetCurrent = () => {
  useArtAddStore.setState((state) => {
    state.current = ArticleSteps.base
  })
}
